using System;
using System.Web;
using FwkLight.Web;
using StructureMap;

namespace FwkLight.Persistence
{
  public class NHUnitOfWorkProvider : INHUnitOfWorkProvider
  {
    private readonly ISessionItemDictionary _sessionItemDictionary;
    private readonly ThreadItemDictionary _threadItemDictionary;

    public NHUnitOfWorkProvider(ISessionItemDictionary sessionItemDictionary,ThreadItemDictionary threadItemDictionary)
    {
      _sessionItemDictionary = sessionItemDictionary;
      _threadItemDictionary = threadItemDictionary;
    }

    public INHUnitOfWork GetCurrentUnitOfWork()
    {
      if (HttpContext.Current != null)
      {
        return GetUowFromHttpContext();
      }
      return GetUowFromThreadContext();
    }

    private INHUnitOfWork GetUowFromThreadContext()
    {
      if (_threadItemDictionary.Contains(PersistenceKeys.CurrentlyRunningLongTransaction))
      {
        if (_threadItemDictionary.Get(PersistenceKeys.CurrentlyRunningLongTransaction))
        {
          return _threadItemDictionary.Get(PersistenceKeys.LongTransactionUnitOfWork);
        }
      }

      return ObjectFactory.GetInstance<INHUnitOfWork>();
    }

    private INHUnitOfWork GetUowFromHttpContext()
    {
      if (_sessionItemDictionary.Contains(PersistenceKeys.CurrentlyRunningLongTransaction))
      {
        if (_sessionItemDictionary.Get(PersistenceKeys.CurrentlyRunningLongTransaction))
        {
          return _sessionItemDictionary.Get(PersistenceKeys.LongTransactionUnitOfWork);
        }
      }

      return ObjectFactory.GetInstance<INHUnitOfWork>();
    }
  }
}